package com.innjia.sys.aop;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.innjia.base.common.ResultInfo;
import com.innjia.base.enums.ContractStatusEnum;
import com.innjia.base.utils.HttpContextUtils;
import com.innjia.base.utils.IPUtils;
import com.innjia.sys.entity.ContractInfoEntity;
import com.innjia.sys.entity.ContractOperationLogEntity;
import com.innjia.sys.entity.UserEntity;
import com.innjia.sys.service.ContractInfoService;
import com.innjia.sys.service.ContractOperationLogService;
import com.innjia.utils.ShiroUtils;

/**
 * 合同操作日志
 * @author fangcheng.huang
 *
 */
@Aspect
@Component
public class ContractLogAspect {

	private static final Logger LOGGER = Logger.getLogger(ContractLogAspect.class);
	
	@Autowired
	private ContractOperationLogService contractOperationLogService;
	
	@Autowired
	private ContractInfoService contractInfoService;
	
	@Pointcut(value = "execution(* com.innjia.sys.service.impl.ContractInfoServiceImpl.*(..))")
	public void logPointCut() { 
		
	}
	
	@AfterReturning(value = "execution(* com.innjia.sys.service.impl.ContractInfoServiceImpl.save*(..))", returning = "rs")
	public void saveContractLog(JoinPoint joinPoint, Object rs) {
		if(joinPoint.getArgs().length == 0) {
			return;
		}
		if(!(joinPoint.getArgs()[0] instanceof ContractInfoEntity)) {
			return;
		}
		ContractInfoEntity entity = (ContractInfoEntity)joinPoint.getArgs()[0];
		String operation = "创建";
		this.insertContractLog(entity, operation, rs);
	}
	
	@AfterReturning(value = "execution(* com.innjia.sys.service.impl.ContractInfoServiceImpl.update*(..))", returning = "rs")
	public void updateContractLog(JoinPoint joinPoint, Object rs) {
		if(joinPoint.getArgs().length == 0) {
			return;
		}
		ContractInfoEntity entity = null;
		if(!(joinPoint.getArgs()[0] instanceof ContractInfoEntity)) {
			if(joinPoint.getArgs()[0] instanceof String) {
				String contractId = (String)joinPoint.getArgs()[0];
				entity = contractInfoService.queryObject(contractId);
			}
		} else {
			entity = (ContractInfoEntity)joinPoint.getArgs()[0];
		}
		if(entity == null) {
			return;
		}
		String operation = "更新";
		this.insertContractLog(entity, operation, rs);
	}
	
	private void insertContractLog(ContractInfoEntity entity, String operation, Object rs) {
		String operateResult = "失败";
		ResultInfo result = null;
		if(rs instanceof Integer) {
			if(((int)rs) == 1) {
				operateResult = "成功";
			}
		} else if(rs instanceof Boolean) {
			if((boolean)rs) {
				operateResult = "成功";
			}
		} else if(rs instanceof ResultInfo) {
			result = (ResultInfo)rs;
		}
		ContractOperationLogEntity log = new ContractOperationLogEntity();
		if(result != null) {
			if("0".equals(result.getCode())) {
				operateResult = "成功";
			} else {
				log.setFailReason(result.getMsg());
			} 
		}
		log.setContractId(entity.getId());
		if(!"0".equals(entity.getContractStatus())) { //签约成功或已作废
			log.setContractStatus(ContractStatusEnum.getDescByCode(entity.getContractStatus()));
		} else { //细分合同状态
			if("0".equals(entity.getSuccessA())) {
				log.setContractStatus("乙方待签约");
			} else {
				log.setContractStatus("甲方待签约");
			}
		}
		log.setCreateTime(new Date());
		log.setOperateResult(operateResult);
		log.setOperateType(operation);
		log.setOperationPlatform(null);
		UserEntity userEntity = null;
		try{
			userEntity = ShiroUtils.getUserEntity();
		} catch (Exception e) {
			LOGGER.info("=============System task execute.");
		}
		if(userEntity == null) {
			log.setOperatorId("系统");
			log.setOperatorName("定时跑批");
			try {
				log.setIp(InetAddress.getLocalHost().getHostAddress());
			} catch (UnknownHostException e) {
				LOGGER.info("");
			}
		} else {
			log.setOperatorId(userEntity.getId());
			log.setOperatorName(userEntity.getUserName());
			HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
			log.setIp(IPUtils.getIpAddr(request));
		}
		contractOperationLogService.save(log);
	}
	
}
